let config = require("../utils/config");
let reconnectCount = 0; // 记录重连次数
let maxReconnectAttempts = 15; // 设置最大重连次数阈值
let goClose = false;
let socketOpen = false;
let args = {};
let heartbeatInterval = null;
function funheartbeatInterval() {
  clearInterval(heartbeatInterval); // 停止发送心跳包
  heartbeatInterval = setInterval(() => {
    wx.sendSocketMessage({
      data: {
        po: "",
        name: "",
        mobile: "",
        head: "",
        msg: "ping",
        type: 99,
      },
      success: function (res) {
        // console.log('发送心跳包成功',heartbeatInterval)
      },
      fail: function (res) {
        // console.log('发送心跳包失败',heartbeatInterval)
        clearInterval(heartbeatInterval); // 停止发送心跳包
        if(!goClose){
          reconnectCount = 0;
          socketOpen = false;
          maxReconnectAttempts = 10;
          reconnectWebSocket(args.openId, args.roomPo, args.callBack);
        }
      }
    });
  }, 60000); // 每1分钟发送一次心跳包
}


let SocketTask = {
  /* 
   * websocket 初始化
  */
  initWebSocket(openId, roomPo, callBack, onconnection) {
    // console.log("websocket：",config.socketUrl + "?a=" + openId +  "&r=" + roomPo)
    if (socketOpen) {
      return;
    }
    args.openId = openId;
    args.roomPo = roomPo;
    args.callBack = callBack;
    wx.connectSocket({
      url: config.socketUrl + "?a=" + openId + "&r=" + roomPo,
      timeout: 3600 * 1000,
      header: {
        'content-type': 'application/json',
      },
    });
    wx.onSocketOpen((result) => {
      console.log("websocket success")
      socketOpen = true;
      // let chatMsg = {
      //   po: roomPo, //房间号
      //   name: config.NICKNAME(),
      //   mobile: config.TEL(),
      //   head: config.HEADURL(),
      //   type: 7, //某某进来了
      // }
      // SocketTask.sendSocketMsg(JSON.stringify(chatMsg));

      try {
        onconnection();
      }
      catch (e) { }

      try {
        funheartbeatInterval();
      }
      catch (e) { }
    })
    wx.onSocketError((result) => {
      console.log("websocket error")
      reconnectWebSocket(openId, roomPo, callBack, onconnection);
    })
    wx.onSocketClose((result) => {
      console.log("websocket closed")
      socketOpen = false;
      if (!goClose){
        reconnectWebSocket(openId, roomPo, callBack, onconnection);
      }
    })
    //监听接收消息
    wx.onSocketMessage((res) => {
      if (!res.data || res.data == "[object Object]"){
        return;
      }
      try {
        let data = JSON.parse(res.data)
        callBack(data);
      } catch (error) {
        console.log("消息类型错误")
      }
    })
  },
  /** socket 发送消息 */
  sendSocketMsg(chatMsg) {
    if (socketOpen) {
      wx.sendSocketMessage({
        data: chatMsg,
        success(res){
          console.log("发送成功")
        },
        fail(e){
          wx.showToast({
            title: '连接已断开，请稍后重试',
            icon: 'none'
          })
        }
      })
    } else {
      reconnectCount = 0;
      maxReconnectAttempts = 10;
      reconnectWebSocket(args.openId, args.roomPo, args.callBack, function () {
        wx.sendSocketMessage({
          data: chatMsg
        });
      });
    }
  },
  /**离开直播间 关闭socket*/
  closeSocket(flag) {
    goClose = flag;
    socketOpen = false;
    reconnectCount = 0;
    maxReconnectAttempts = 10;
    if(heartbeatInterval){
      clearInterval(heartbeatInterval)
    }
    try {
      wx.closeSocket();
    }
    catch (e) {

    }
  }
};

function reconnectWebSocket(openId, roomPo, onMessageCallback, onconnection) {
  if (!socketOpen) {
    if (reconnectCount < maxReconnectAttempts) {
      console.log(`正在尝试重新连接WebSocket，第 ${reconnectCount + 1} 次...`);
      reconnectCount++;
      SocketTask.initWebSocket(openId, roomPo, onMessageCallback, onconnection);
    } else {
      console.log(`已超过最大重连次数，放弃重连`);
      // 在这里可以做放弃重连后的处理
    }
  }
}

module.exports = {
  SocketTask: SocketTask
}